import { useState, useMemo } from 'react'

export interface SearchableItem {
  id: string
  title: string
  content: string
  category?: string
  date?: string
  type: 'moment' | 'letter' | 'note' | 'bucket' | 'story'
}

export function useSearch<T extends SearchableItem>(items: T[]) {
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState('all')

  const filteredItems = useMemo(() => {
    let filtered = items

    // 按类别筛选
    if (selectedCategory !== 'all') {
      filtered = filtered.filter(item => item.category === selectedCategory)
    }

    // 按搜索关键词筛选
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim()
      filtered = filtered.filter(item => 
        item.title.toLowerCase().includes(query) ||
        item.content.toLowerCase().includes(query) ||
        (item.category && item.category.toLowerCase().includes(query)) ||
        (item.date && item.date.includes(query))
      )
    }

    return filtered
  }, [items, searchQuery, selectedCategory])

  const categories = useMemo(() => {
    const cats = new Set(items.map(item => item.category).filter(Boolean))
    return Array.from(cats)
  }, [items])

  return {
    searchQuery,
    setSearchQuery,
    selectedCategory,
    setSelectedCategory,
    filteredItems,
    categories,
    hasResults: filteredItems.length > 0,
    totalItems: items.length,
    filteredCount: filteredItems.length
  }
}
